<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\goods;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;


class  CarController extends Controller
{	
	//加入购物车操作
	public function insert(Request $request){
		// dd($request->all());
		// $goods = session('car');
		// 	dd($goods);
		
		//提取数据
		$data = $request->only('id','num');
		// dd($data['id']);
		//检测当前数据是否存在购物车中
		if($this->check($data['id'])){
			//购物车商品存在 进行数量添加
			$goods = session('car');
			// dd($goods);
			foreach($goods as $k=>$v){
				if($v['id'] == $data['id']){
					$goods[$k]['num'] += $data['num'];
				}

				session(['car'=>$goods]);
			}
		}else{

		//将当前数据压入session中
		 $request->session()->push('car',$data);
		}
		// dd(session('car'));
		// $this->index();
		return redirect('/shopcar/index');
	}

	// 检测购物车中的商品是否存在
	private function check($id){
		//读取购物车信息
		$goods = session('car');
		// dd($goods);
		if(empty($goods)){
			return false;
		}
		//有数据 return 返回
		foreach ($goods as $k => $v) {
			if($v['id'] == $id){
				//商品在购物车中
				return true;

			}
		}
		//商品不在购物车中
		return false;
	}

	//显示购物车中的信息
	public function index(Request $request){
		$goods = session('car');
		// dd($goods);
		//根据商品id查询商品信息
		$data = [];
		// 总计
		$total =0;
		// 小计
		$xiaoji=0;
		$totalnum=0;
		if(!empty($goods) ){
		foreach ($goods as $k => $v) {
			// var_dump($id=$v['id']);
			// $id = $v->id;
			// dd($v);
			if($v['id'] !=null){
			$tmp = Goods::find($v['id']);
			$tmp->num = $v['num'];
			// dd($tmp);
			$xiaoji = $tmp->price * $tmp->num;
			$tmp->xiaoji=$xiaoji;
			$total+=$xiaoji;
			$totalnum+=$tmp->num;

			$data[] = $tmp;
			}
		}
		
		// dd($data);
		return view('goods.shopcar',['goods'=>$data,'total'=>$total]);
			
	}else{
		return view('goods.emptycar');
	}
	}

	//清空购物车
	public function clear(Request $request){
		$request->session()->forget('car');
		// dd($goods);
		return view('goods.emptycar');
	}

	//删除购物车中的商品 id
	public function delete(Request $request){
		$id=$request->input('id');
		// dd($id);
		//删除session中指定的元素
		$data = session('car');
		//遍历
		foreach ($data as $k => $v) {
			if($v['id'] == $id){
				unset($data[$k]);
			}
		}
		session(['car'=>$data]);
		echo 1;
	}
}

